package com.lsk.mobile;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.google.gson.Gson;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.lsk.alipay.alipaylife.AlipayConfig;
import com.lsk.alipay.alipaylife.AlipaySubmit;
import com.lsk.alipay.common.MyException;
import com.lsk.alipay.constants.AlipayServiceEnvConstants;
import com.lsk.alipay.dispatcher.Dispatcher;
import com.lsk.alipay.executor.ActionExecutor;
import com.lsk.alipay.servlet.gateway.GatewayServlet;
import com.lsk.alipay.util.LogUtil;
import com.lsk.alipay.util.RequestUtil;
import com.lsk.util.*;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 支付宝小程序
 */
public class ApplyController extends Controller {
    Cache cache = Redis.use();
    static MobileServices mobileServices = new MobileServices();

    AppletService appletService = Duang.duang(new AppletService());

    ApplyService applyService = Duang.duang(new ApplyService());

    String zhifubaoDomain="ajy.19xw.net";



    /**
     * getUserId
     *
     * @return
     */
    public void getUserId() {

        String code = getPara("code");

        ReturnData returnData = applyService.getUserId(code);

        renderJson(returnData);
    }

    /**
     * 支付宝生活号验证
     */
    @Clear
    public void dispatcher() {

        String responseMsg = "";

        try {
            HttpServletRequest request = getRequest();

            HttpServletResponse response = getResponse();
            //支付宝响应消息


            //1. 解析请求参数
            Map<String, String> params = RequestUtil.getRequestParams(request);

            //打印本次请求日志，开发者自行决定是否需要
            LogUtil.log("支付宝请求串", params.toString());

            try {
                //2. 验证签名
                //applyService.verifySign(params);

                //3. 获取业务执行器   根据请求中的 service, msgType, eventType, actionParam 确定执行器
                ActionExecutor executor = Dispatcher.getExecutor(params);

                //4. 执行业务逻辑
                responseMsg = executor.execute();

            }/* catch (AlipayApiException alipayApiException) {

                System.out.println("异常1");

                //开发者可以根据异常自行进行处理
                alipayApiException.printStackTrace();

            }*/ catch (Exception exception) {
                //开发者可以根据异常自行进行处理
                exception.printStackTrace();
                System.out.println("异常2");
            } finally {


                /*给支付宝变量赋值*/

                String applySql = "SELECT `value` from sys_config where element=";

                String applyAppId = Db.queryStr(applySql + "'applyAppId'");

                String applyPublicKey = Db.queryStr(applySql + "'applyPublicKey'");


                String applyPrivateKey = Db.queryStr(applySql + "'applyPrivateKey'");

//                AlipayServiceEnvConstants.APP_ID=applyAppId;
//
//                AlipayServiceEnvConstants.PRIVATE_KEY=applyPrivateKey;
//
//                AlipayServiceEnvConstants.PUBLIC_KEY=applyPublicKey;


                //5. 响应结果加签及返回
                try {

                    System.out.println("网管验签开始");
                    //对响应内容加签
                    responseMsg = applyService.encryptAndSign(responseMsg,
                            AlipayServiceEnvConstants.ALIPAY_PUBLIC_KEY.trim(),
                            AlipayServiceEnvConstants.PRIVATE_KEY.trim(), AlipayServiceEnvConstants.CHARSET,
                            false, true, AlipayServiceEnvConstants.SIGN_TYPE);

                    System.out.println("网管验签结束");

                    System.out.println("*************************");

                    System.out.println(responseMsg);

                    //http 内容应答


                    //开发者自行决定是否要记录，视自己需求
                    //LogUtil.log("开发者响应串", responseMsg);

                } catch (AlipayApiException alipayApiException) {
                    //开发者可以根据异常自行进行处理
                    alipayApiException.printStackTrace();
                }
            }
        } catch (Exception e) {
            Syslog.error(e);
        }


        System.out.println("相应内容：" + responseMsg);

        renderText(responseMsg);
    }


    //请求支付宝接口获取auth_code
    public void login() throws AlipayApiException {

        String classId = getPara("classId");

        String applyType = getPara("applyType");

        switch (classId) {

            case "jiayouka":
                classId = "964f4b2ecacf4ab8afcb038a4deb69a7";
                break;
            case "gouwuka":
                classId = "8ad0d4de05384d2c87b0c0e9874dbdf6";
                break;
            case "dianshangka":
                classId = "9ec875bf2a244f7f92d3f81bb9b18363";
                break;
            case "huafeika":
                classId = "16ffa348f1754997baec00d45ce44ca8";
                break;
            case "youxika":
                classId = "d844f4950b4b4b88ab4a048616e95a01";
                break;
            case "meshika":
                classId = "312bc982621047eebe7f262323772c63";
                break;
            default:
                Syslog.info("去首页的路径");

        }

        if (applyType != null) {//柠檬时代的链接


            applyType = "2";


        } else {

            applyType = "2";//邦邦
        }


        setCookie("classId", classId, 3);

        Map<String, String> maps = new HashMap<String, String>();

        String sql = "SELECT `value` from sys_config where element=";

        String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址


        String applyAppId = Db.queryStr(sql + "'applyAppId'");
        //String applyAppId= AlipayServiceEnvConstants.APP_ID;
        //页面回调地址 必须与应用中的设置一样
        String return_url = "http://" + domain + "/apply/authorization?classId=" + classId + "&applyType=" + applyType;

        Syslog.log.info("url:" + "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
                + "?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url);

        //回调地址必须经encode
        return_url = java.net.URLEncoder.encode(return_url);


        //重定向到授权页面
        redirect("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
                + "?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url);

    }

    //回调地址获取用户user_id和用户信息
    @Clear
    public void authorization() throws AlipayApiException {

        Syslog.info("支付宝授权回调");

        String token = "";

        ReturnData returnData = new ReturnData();
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<Map, Map> map = new HashMap(); //转化返回的json字符串
        Map requestParams = getRequest().getParameterMap();


        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == (values.length - 1)) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        Syslog.info("*************     " + JsonUtil.getJsonStr(params));

        String accessToken = AlipaySubmit.buildRequest(params);

        try {
            if (accessToken != null && accessToken != "") {
                String imf = AlipaySubmit.get(accessToken);
                Gson gson = new Gson();
                map = gson.fromJson(imf, map.getClass());
                System.out.println(imf);
                String userId = map.get("alipay_user_info_share_response").get("user_id").toString();
                //用户昵称
                String nick_name = map.get("alipay_user_info_share_response").get("nick_name") + "";

                //用户头像
                String heardUrl = map.get("alipay_user_info_share_response").get("avatar") + "";

                Syslog.info("用户支付宝id为：" + userId);


                returnData = appletService.apiupMemberService(userId, nick_name, heardUrl);

                Map tokenMap = (Map) returnData.getData();

                token = (String) tokenMap.get("token");

                setCookie("token", token, 60 * 60 * 24);
            }
        } catch (Exception e) {
            e.printStackTrace();

            Syslog.info("验证签名失败，无视他");
        }
        setCookie("type", "2", 60 * 60 * 24);

        String classId = getPara("classId");//类别id


        String sql = "SELECT `value` from sys_config where element=";


        String domain = Db.queryStr(sql + "'domain'").replace("http://", "");  //服务器域名地址

        domain =zhifubaoDomain;

        String applyType = getPara("applyType");

        String redirectUrl = "http://" + domain + "/#/pages/authorize/authorize?token=" + token + "&classId=" + classId + "&applyType=" + applyType;

        Syslog.info(redirectUrl);

        redirect(redirectUrl);

    }

    /**
     * 支付宝
     */

    /**
     * 支付宝小程序授权
     */
    public void applyAuthorization() {

        String code = getPara("code");

        String name = getPara("name");

        ReturnData returnData = applyService.getApplyUserId(code, name);

        renderJson(returnData);

    }


    /**
     * 保存数据
     */
    public void saveData() {
        Map data = getParaMap();
        cache.setex("data", 10 * 60, data);
        Object o = cache.get(data);
        Syslog.info(o);
        ReturnData rd = new ReturnData();
        rd.setResult(true);
        renderJson(rd);
    }


    /**
     * 交易记录
     */
    //请求支付宝接口获取auth_code
    public void transfer() throws AlipayApiException {

        String redirctUrl = getPara("uri");

        Syslog.info("重定向网址为：" + redirctUrl);

        setCookie("transferUri", redirctUrl, 60);

        String sql = "SELECT `value` from sys_config where element=";

        String domain = Db.queryStr(sql + "'domain'");  //服务器域名地址

        String applyAppId = Db.queryStr(sql + "'limoAppId'");
        //页面回调地址 必须与应用中的设置一样
        String return_url = "http://" + domain + "/limo/toMyAuthorization";
        Syslog.info("重定向地址" + return_url);
        //回调地址必须经encode
        return_url = java.net.URLEncoder.encode(return_url);
        //重定向到授权页面
        String redirectUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
                + "?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url;
        Syslog.info("发起重定向地址为：" + redirectUrl);

        redirect(redirectUrl);

    }


    //请求支付宝接口获取auth_code
    public void orderLogin() throws AlipayApiException {


        Map<String, String> maps = new HashMap<String, String>();

        String sql = "SELECT `value` from sys_config where element=";
        //String domain= Db.queryStr(sql+"'domain'");  //服务器域名地址
        String domain = "apihzijy.19xw.net";
        String applyAppId = Db.queryStr(sql + "'applyAppId'");
        //String applyAppId= AlipayServiceEnvConstants.APP_ID;
        //页面回调地址 必须与应用中的设置一样
        String return_url = "http://" + domain + "/apply/orderAuthorization";

        Syslog.log.info("url:" + "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
                + "?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url);

        //回调地址必须经encode
        return_url = java.net.URLEncoder.encode(return_url);


        //重定向到授权页面
        redirect("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
                + "?app_id=" + applyAppId + "&scope=auth_user&redirect_uri=" + return_url);

    }
    /**
     * 交易记录回调
     */
    public void orderAuthorization(){


        Syslog.info("支付宝授权回调（订单记录）");

        String token = "";

        ReturnData returnData = new ReturnData();
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<Map, Map> map = new HashMap(); //转化返回的json字符串
        Map requestParams = getRequest().getParameterMap();


        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == (values.length - 1)) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        Syslog.info("*************     " + JsonUtil.getJsonStr(params));



        try {
            String accessToken = AlipaySubmit.buildRequest(params);


            if (accessToken != null && accessToken != "") {
                String imf = AlipaySubmit.get(accessToken);
                Gson gson = new Gson();
                map = gson.fromJson(imf, map.getClass());
                System.out.println(imf);
                String userId = map.get("alipay_user_info_share_response").get("user_id").toString();
                //用户昵称
                String nick_name = map.get("alipay_user_info_share_response").get("nick_name") + "";

                //用户头像
                String heardUrl = map.get("alipay_user_info_share_response").get("avatar") + "";

                Syslog.info("用户支付宝id为：" + userId);


                returnData = appletService.apiupMemberService(userId, nick_name, heardUrl);

                Map tokenMap = (Map) returnData.getData();

                token = (String) tokenMap.get("token");

                setCookie("token", token, 60 * 60 * 24);
            }
        } catch (Exception e) {
            e.printStackTrace();

            Syslog.info("验证签名失败，无视他");
        }
        setCookie("type", "3", 60 * 60 * 24);

        String classId = getPara("classId");//类别id


        String sql = "SELECT `value` from sys_config where element=";


        String domain = Db.queryStr(sql + "'domain'").replace("http://", "");  //服务器域名地址

        domain = zhifubaoDomain;


        String redirectUrl = "http://" + domain + "/#/pages/authorize1/authorize1?token=" + token ;

        Syslog.info(redirectUrl);

        redirect(redirectUrl);


    }



}









